let OSSIMGURL = "https://hykoc.oss-cn-beijing.aliyuncs.com/";
class OssUpload {
	constructor() {
		this.signature = '';
	}
	getSignatue() {
		if (this.signature) {
			return Promise.resolve(this.signature);
		} else {
			return new Promise((resolve, reject) => {
				return uni.request({
					url: "https://getkoc.hylinkad.com/public/oss-sign-ticket",
					method: "GET"
				}).then(res => {
					if (res.statusCode === 200 && res.data.code === 0) {
						resolve(res.data.data)
					} else {
						uni.showToast({
							icon: 'error',
							title: '网络错误，请稍后重试'
						})
					}
				}).catch(err => {
					uni.showToast({
						icon: 'error',
						title: '网络错误，请稍后重试'
					})
				});
			});
		}
	}

	upload(filePath, reset = true) {
		if (reset) {
			this.reset();
		}
		return this.getSignatue().then((s) => {
			const filename =
				`${new Date().getTime()}_${filePath.substring(filePath.lastIndexOf('tmp') + 4)}`; //_${item.name}
			const key = `${s.dir}${filename}`;
			if (s.host) {
				OSSIMGURL = `${s.host}/`
			}
			console.log(key, 'key')
			const formData = {
				key,
				policy: s.policy,
				OSSAccessKeyId: s.accessid,
				signature: s.signature,
				callback: s.callback
			}
			console.log(formData, 'formData')
			return new Promise((resolve, reject) => {
				return uni.uploadFile({
					url: s.host,
					filePath,
					name: 'file',
					header: {
						"x-oss-object-acl": "public-read",
						"Access-Control-Allow-Origin": "*"
					},
					formData,
					success: (uploadFileRes) => {
						console.log(uploadFileRes, OSSIMGURL + key);
						if (uploadFileRes.statusCode === 200) {
							resolve({
								...uploadFileRes,
								key: OSSIMGURL + key
							})
						} else {
							uni.showToast({
								icon: 'error',
								title: '网络错误，请稍后重试'
							})
						}
					},
					fail: () => {
						uni.showToast({
							icon: 'error',
							title: '网络错误，请稍后重试'
						})
					},
					complete:(res) => {
						console.log(res)
					}
				})
			})

			

		});
	}

	reset() {
		this.signature = undefined;
	}
}
// 导出一个实例对象
export default new OssUpload();